package com.wuye.service;

import com.wuye.model.option.Questionnaire;
import com.wuye.repository.QuestionnaireRepository;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Component
public class QuestionnaireJob implements InitializingBean {
    private static Logger log = LogManager.getLogger(QuestionnaireJob.class);
    @Autowired
    QuestionnaireRepository questionnaireRepository;

    // 每小时30分触发-
    @Scheduled(cron = "0 0/30 * * * ?")
    @Transactional(rollbackFor = Exception.class, readOnly = false)
    public void collageEndJob() {
        Date now = new Date();
        List<Questionnaire> questionnaires = questionnaireRepository.findUnFinished();
        for (Questionnaire q : questionnaires) {
            int s;
            if (now.getTime() > q.getEndTime().getTime()) {
                s = 2;
            } else if (now.getTime() > q.getPublishTime().getTime() && now.getTime() < q.getEndTime().getTime()) {
                s = 1;
            } else {
                s = 0;
            }
            if(s != q.getState()) {
                q.setState(s);
                questionnaireRepository.save(q);
            }
        }

    }


    @Override
    public void afterPropertiesSet() throws Exception {

    }
}
